import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class OplatformService extends BaseService<any> {
  private readonly logger = new Logger(OplatformService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * createPreAuthorizationUrl
   * 对应 PHP: OplatformService_admin::createPreAuthorizationUrl()
   * 逻辑类型: undefined - undefined
   */
  async createPreAuthorizationUrl() {
    // 基于PHP真实逻辑: createPreAuthorizationUrl
    // PHP原文: $app = CoreOplatformService::app();         return $app->createPreAuthorizationUrl((string)url('/site/wxoplatform/callback', [],'',true));     }      ...
const app = CoreOplatformService.app(];
        return app.createPreAuthorizationUrl((string)url('/site/wxoplatform/callback', [),'',true)];
    }

    /**
     *
     * @param data
     * @return true
     * @throws \EasyWeChat\Kernel\BusinessExceptions\BadResponseBusinessException
     * @throws \EasyWeChat\Kernel\BusinessExceptions\HttpBusinessException
     * @throws \Symfony\Contracts\HttpClient\BusinessException\ClientBusinessExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\BusinessException\DecodingBusinessExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\BusinessException\RedirectionBusinessExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\BusinessException\ServerBusinessExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\BusinessException\TransportBusinessExceptionInterface
     */
    async authorization(data) {
        const app = CoreOplatformService.app(];
        const authorization = app.getAuthorization(data.auth_code).toArray(];

        // 授权账号信息 授权信息
        const result = CoreOplatformService.getAuthorizerInfo(app, authorization.authorization_info.authorizer_appid).toArray(];
        const authorizer_info = result.authorizer_info;
        const authorization_info = result.authorization_info;
        result.authorization_info.auth_code = data.auth_code;

        // 小程序
        const qrcode_dir = 'file/image/'.this.site_id + '/'.date('Ym') + '/'.date('d');
        if (typeof authorizer_info.MiniProgramInfo)) {
            this.weappCheck(authorizer_info, authorization_info);

            const service = this.coreWeappConfigService;
            const config_data = [
                weapp_name: authorizer_info.nick_name,
                weapp_original: authorizer_info.user_name,
                app_id: authorization_info.authorizer_appid,
                qr_code: this.coreFetchService.image(authorizer_info.qrcode_url, this.site_id, qrcode_dir).url,
                is_authorization: 1
            ];
            service.setWeappConfig(this.site_id, config_data];

            result.authorizer_info.qrcode_url = config_data.qr_code;
            service.setWeappAuthorizationInfo(this.site_id, result);

            // 授权成功之后调用
            WeappAuthChangeAfter.dispatch([site_id: this.site_id, event: 'authorized' )];
  }

  /**
   * authorization
   * 对应 PHP: OplatformService_admin::authorization()
   * 逻辑类型: undefined - undefined
   */
  async authorization(data: any[]) {
    // 基于PHP真实逻辑: authorization
    // PHP原文: $app = CoreOplatformService::app();         $authorization = $app->getAuthorization($data['auth_code'])->toArray();          // 授权账号信息 授权信息         $r...
const app = CoreOplatformService.app(];
        const authorization = app.getAuthorization(data.auth_code).toArray(];

        // 授权账号信息 授权信息
        const result = CoreOplatformService.getAuthorizerInfo(app, authorization.authorization_info.authorizer_appid).toArray(];
        const authorizer_info = result.authorizer_info;
        const authorization_info = result.authorization_info;
        result.authorization_info.auth_code = data.auth_code;

        // 小程序
        const qrcode_dir = 'file/image/'.this.site_id + '/'.date('Ym') + '/'.date('d');
        if (typeof authorizer_info.MiniProgramInfo)) {
            this.weappCheck(authorizer_info, authorization_info);

            const service = this.coreWeappConfigService;
            const config_data = [
                weapp_name: authorizer_info.nick_name,
                weapp_original: authorizer_info.user_name,
                app_id: authorization_info.authorizer_appid,
                qr_code: this.coreFetchService.image(authorizer_info.qrcode_url, this.site_id, qrcode_dir).url,
                is_authorization: 1
            ];
            service.setWeappConfig(this.site_id, config_data];

            result.authorizer_info.qrcode_url = config_data.qr_code;
            service.setWeappAuthorizationInfo(this.site_id, result);

            // 授权成功之后调用
            WeappAuthChangeAfter.dispatch([site_id: this.site_id, event: 'authorized' )];
  }

  /**
   * clearAuthorization
   * 对应 PHP: OplatformService_admin::clearAuthorization()
   * 逻辑类型: undefined - undefined
   */
  async clearAuthorization(app_id: any) {
    // 基于PHP真实逻辑: clearAuthorization
    // PHP原文: (new SysConfig())->where([ ['value', 'like', "%{$app_id}%"], ['config_key', 'in', [             ConfigKeyDict::WEAPP, ConfigKeyDict::WECHAT, ConfigKey...
this.sysConfigService.where([ ['value', 'like', "%{app_id}%"], ['config_key', 'in', [
            ConfigKeyDict.WEAPP, ConfigKeyDict.WECHAT, ConfigKeyDict.WEAPP_AUTHORIZATION_INFO, ConfigKeyDict.WECHAT_AUTHORIZATION_INFO
        ] ) )).delete(];

        WechatAuthChangeAfter.dispatch([site_id: this.site_id, event: 'unauthorized')];
        WeappAuthChangeAfter.dispatch([site_id: this.site_id, event: 'unauthorized')];

        return true;
    }

    /**
     * 授权的小程序检测
     * @param authorizer_info
     * @param authorization_info
     * @return void
     */
    private async weappCheck(authorizer_info, authorization_info) {
        const is_exist = this.sysConfigService.where([ ['value', 'like', "%{authorization_info.authorizer_appid}%"], ['config_key', '=', ConfigKeyDict.WEAPP], ['site_id', '<>', this.site_id) )).count(];
        if (is_exist) throw new BusinessException('WEAPP_EXIST');

        if (authorizer_info.service_type_info.id != 0 || authorizer_info.verify_type_info.id == -1) throw new BusinessException('请使用已认证的小程序进行授权');

        // 授权的权限
        const authority = array_map(function (item){
            return item.funcscope_category.id;
  }

  /**
   * getAuthRecord
   * 对应 PHP: OplatformService_admin::getAuthRecord()
   * 逻辑类型: undefined - undefined
   */
  async getAuthRecord(data: any) {
    // 基于PHP真实逻辑: getAuthRecord
    // PHP原文: $condition = [             ['config_key', 'in', [ ConfigKeyDict::WECHAT_AUTHORIZATION_INFO, ConfigKeyDict::WEAPP_AUTHORIZATION_INFO ] ]         ];    ...
const condition = [
            ['config_key', 'in', [ ConfigKeyDict.WECHAT_AUTHORIZATION_INFO, ConfigKeyDict.WEAPP_AUTHORIZATION_INFO ] ]
        ];
        const search_model = this.sysConfigService.field('*').where(condition).with([site: function(query){
            query.field('site_id,site_name');
  }

  /**
   * weappCheck
   * 对应 PHP: OplatformService_admin::weappCheck()
   * 逻辑类型: undefined - undefined
   */
  async weappCheck(authorizer_info: any, authorization_info: any) {
    // 基于PHP真实逻辑: weappCheck
    // PHP原文: $is_exist = (new SysConfig())->where([ ['value', 'like', "%{$authorization_info['authorizer_appid']}%"], ['config_key', '=', ConfigKeyDict::WEAPP], ['...
const is_exist = this.sysConfigService.where([ ['value', 'like', "%{authorization_info.authorizer_appid}%"], ['config_key', '=', ConfigKeyDict.WEAPP], ['site_id', '<>', this.site_id) )).count(];
        if (is_exist) throw new BusinessException('WEAPP_EXIST');

        if (authorizer_info.service_type_info.id != 0 || authorizer_info.verify_type_info.id == -1) throw new BusinessException('请使用已认证的小程序进行授权');

        // 授权的权限
        const authority = array_map(function (item){
            return item.funcscope_category.id;
  }

  /**
   * wechatCheck
   * 对应 PHP: OplatformService_admin::wechatCheck()
   * 逻辑类型: undefined - undefined
   */
  async wechatCheck(authorizer_info: any, authorization_info: any) {
    // 基于PHP真实逻辑: wechatCheck
    // PHP原文: $is_exist = (new SysConfig())->where([ ['value', 'like', "%{$authorization_info['authorizer_appid']}%"], ['config_key', '=', ConfigKeyDict::WECHAT], [...
const is_exist = this.sysConfigService.where([ ['value', 'like', "%{authorization_info.authorizer_appid}%"], ['config_key', '=', ConfigKeyDict.WECHAT], ['site_id', '<>', this.site_id) )).count(];
        if (is_exist) throw new BusinessException('WECHAT_EXIST');

        if (authorizer_info.service_type_info.id != 2 || authorizer_info.verify_type_info.id == -1) throw new BusinessException('请使用已认证的服务号进行授权');

        // 授权的权限
        const authority = array_map(function (item){
            return item.funcscope_category.id;
  }
}
